<template>
    <div>
        <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
        >
            <div class="el-form-content">
                <div class="el-form-items">
                    <el-form-item
                        label="姓名"
                        prop="nickName"
                        label-width="120px"
                    >
                        <el-input
                            v-model="ruleForm.nickName"
                            placeholder="请输入姓名"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="出生日期" label-width="120px">
                        <el-date-picker
                            value-format="yyyy-MM-dd"
                            type="date"
                            placeholder="选择日期"
                            v-model="ruleForm.birthday"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="签发机关" label-width="120px">
                        <el-input
                            v-model="ruleForm.idIssued"
                            placeholder="请输入签发机关"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="有效截止期限" label-width="120px">
                        <el-date-picker
                            value-format="yyyy-MM-dd"
                            type="date"
                            placeholder="选择截止期限"
                            v-model="ruleForm.issuedValidDate"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item
                        label="手机号码"
                        prop="phonenumber"
                        label-width="120px"
                    >
                        <el-input
                            v-model="ruleForm.phonenumber"
                            placeholder="请输入手机号码"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="用户性别"
                        prop="sex"
                        label-width="120px"
                    >
                        <el-select v-model="ruleForm.sex">
                            <el-option
                                v-for="dict in sexOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="角色"
                        prop="roleIds"
                        label-width="120px"
                    >
                        <el-select
                            v-model="ruleForm.roleIds"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="item in roleOptions"
                                :key="item.roleId"
                                :label="item.roleName"
                                :value="item.roleId"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="血型" label-width="120px">
                        <el-input
                            v-model="ruleForm.bloodType"
                            placeholder="血型"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="紧急联系人" label-width="120px">
                        <el-input
                            v-model="ruleForm.emergencyContactPer"
                            placeholder="请输入紧急联系人"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="紧急联系人电话"
                        label-width="120px"
                        prop="emergencyContactPh"
                    >
                        <el-input
                            v-model="ruleForm.emergencyContactPh"
                            placeholder="请输入紧急联系人电话"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="籍贯" label-width="120px">
                        <el-input
                            v-model="ruleForm.nativePlace"
                            placeholder="请输入籍贯"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="工种" label-width="120px">
                        <el-input
                            :disabled="true"
                            v-model="ruleForm.workTypeName"
                        ></el-input>
                    </el-form-item>
                </div>
                <div class="el-form-items">
                    <el-form-item label="证件号码" prop="certNumber">
                        <el-input
                            v-model="ruleForm.certNumber"
                            placeholder="请输入证件号码"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="民族">
                        <el-input
                            v-model="ruleForm.nation"
                            placeholder="请输入民族"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="家庭地址">
                        <el-input
                            v-model="ruleForm.address"
                            placeholder="请输入家庭地址"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="所属单位" prop="deptId">
                        <treeselect
                            v-model="ruleForm.deptId"
                            :options="deptOptions"
                            :disable-branch-nodes="false"
                            :show-count="true"
                            placeholder="请选择归属部门"
                        />
                    </el-form-item>
                    <el-form-item label="芯片编号">
                        <el-input
                            v-model="ruleForm.cardNum"
                            placeholder="请输入芯片编号"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="过往病史">
                        <el-input
                            v-model="ruleForm.medicalHistory"
                            placeholder="请输入过往病史"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="进场时间">
                        <el-input
                            :disabled="true"
                            v-model="ruleForm.indate"
                            placeholder="请选择进场时间"
                        ></el-input>
                    </el-form-item>
                    <div class="user-code">
                        <div>
                            <img
                                v-if="ruleForm.srcImg != ''"
                                :src="ruleForm.srcImg"
                            />
                            <img
                                v-else-if="ruleForm.avatar != ''"
                                :src="ruleForm.avatar"
                            />
                            <img
                                v-else
                                src="@/assets/image/userImage.png"
                                alt=""
                                srcset=""
                            />
                            <p>(尺寸大小120×140)</p>
                            <el-button @click="onFresh" type="warning"
                                >获取身份证信息</el-button
                            >
                        </div>
                        <div>
                            <div id="qrcode"></div>
                        </div>
                    </div>
                </div>
            </div>
            <el-form-item class="btns">
                <el-button type="primary" @click="submitForm('ruleForm')"
                    >保存</el-button
                >
                <el-button @click="closePage">关闭</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { getUser, updateUser } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import QRCode from "qrcodejs2";

import errors, { base64ToFile } from "@/api/idcard/idcard";
import axios from 'axios';

export default {
    name: 'userInfo',
    components: { Treeselect, QRCode, errors, axios },
    data () {
        var checkphone = (rule, value, callback) => {
            let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
            if (value == "") {
                callback(new Error("请输入手机号"));
            } else if (!phoneReg.test(value)) {//引入methods中封装的检查手机格式的方法
                callback(new Error("请输入正确的手机号!"));
            } else {
                callback();
            }
        }
        var checkphone1 = (rule, value, callback) => {
            let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
            if (value == "") {
                callback();
            } else if (!phoneReg.test(value)) {//引入methods中封装的检查手机格式的方法
                callback(new Error("请输入正确的手机号"));
            } else {
                callback();
            }
        }
        var checkIdcard = (rule, value, callback) => {
            let idCardReg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
            if (value == "") {
                callback();
            } else if (!idCardReg.test(value)) {//引入methods中封装的检查手机格式的方法
                callback(new Error("请输入正确的身份证!"));
            } else {
                callback();
            }
        }
        return {
            ruleForm: {
                nickName: '', // 姓名
                birthday: '', // 出生日期
                idIssued: '', // 签发机关
                issuedValidDate: '', //有效截止期限
                phonenumber: '',// 手机号码
                sex: '', // 用户性别
                roleIds: '', // 角色
                bloodType: '', // 血型
                emergencyContactPer: '', // 紧急联系人
                emergencyContactPh: '', // 紧急联系人电话
                nativePlace: '', // 籍贯
                workTypeName: '', // 工种
                certNumber: '', // 证件号码
                nation: '', // 民族
                address: '', // 家庭地址
                deptId: '', // 所属单位
                cardNum: '', // 芯片编号
                indate: '', //  进场时间
                avatar: '' //头像
            },
            deptOptions: undefined,
            workTypeOptions: [],
            sexOptions: [],
            roleOptions: [],
            rules: {
                nickName: [
                    { required: true, message: '请输入姓名', trigger: ['blur', 'change'] }
                ],
                phonenumber: [
                    { required: true, validator: checkphone, trigger: ['blur', 'change'] }
                ],
                sex: [
                    { required: true, message: '请选择用户性别', trigger: ['blur', 'change'] }
                ],
                roleIds: [
                    { required: true, message: '请选择用户角色', trigger: ['blur', 'change'] }
                ],
                emergencyContactPh: [
                    { required: false, validator: checkphone1, trigger: ['blur', 'change'] }
                ],
                workTypeName: [
                    { required: true, message: '请选择工种', trigger: ['blur', 'change'] }
                ],
                certNumber: [
                    { required: true, validator: checkIdcard, trigger: ['blur', 'change'] }
                ],
                deptId: [
                    { required: true, message: '请选择单位', trigger: ['blur', 'change'] }
                ],
                indate: [
                    { required: true, message: '请选择进场时间', trigger: ['blur', 'change'] }
                ]
            }
        };
    },
    created () {
        this.getTreeselect()
        this.getDicts("work_type").then(response => {
            this.workTypeOptions = response.data;
        });
        this.getDicts("sys_user_sex").then(response => {
            this.sexOptions = response.data;
        });
        this.getUser()
    },
    mounted () {
        this.qrcode()
    },
    methods: {
        qrcode () {
            let that = this;
            let qrcode = new QRCode('qrcode', {
                width: 110,
                height: 110,        // 高度
                text: `smart_userid_${this.$route.params.id}`,   // 二维码内容
            })
        },
        submitForm (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.updateUser()
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        async updateUser () {
            let params = JSON.parse(JSON.stringify(this.ruleForm))
            for (let i = 0; i < this.workTypeOptions.length; i++) {
                if (params.workTypeName == this.workTypeOptions[i].dictLabel) {
                    params.workTypeName = this.workTypeOptions[i].dictValue
                    break
                }
            }
            params.roleIds = [params.roleIds]
            delete params.roles
            delete params.postIds
            let res = await updateUser(params)
            if (res.code == 200) {
                this.closePage()
            }
        },
        resetForm (formName) {
            this.$refs[formName].resetFields();
        },
        /** 查询部门下拉树结构 */
        getTreeselect () {
            treeselect().then(response => {
                this.deptOptions = response.data;
            });
        },
        async getUser () {
            let res = await getUser(this.$route.params.id)
            if (res.code == 200) {
                this.roleOptions = res.roles;
                this.ruleForm = res.data
                this.ruleForm.roleIds = this.ruleForm.roles[0].roleId
                this.ruleForm.workTypeName = res.pPost.workType
                this.ruleForm.indate = res.pPost.indate
            }
        },
        closePage () {
            let view = this.$route
            // this.$parent.$parent.$parent.$parent.$parent.$children[2].closeSelectedTag(view)
            // console.log(this.$parent.$parent.$parent.$parent.$parent.$children[3].$children[1])
            this.$parent.$parent.$parent.$parent.$parent.$children[3].$children[1].closeSelectedTag(view)

        },
        //刷身份证获取信息
        onFresh () {
            var l = this.$loading({
                lock: true,
                text: "读取中..."
            });
            this.loading = true;
            let base = {
                "http:": 24010,
                "https:": 24011
            };
            let url = `${location.protocol}//127.0.0.1:${
                base[location.protocol]
                }/ZKIDROnline/ScanReadIdCardInfo?OP-DEV=1&CMD-URL=4&REPEAT=1&common=1&random=` + parseInt(Math.random() * 10000);

            axios.get(url).then((res = {}) => {
                l.close();
                // console.log(res);
                let ret = res.data.ret;
                let Certificate = res.data.Certificate;
                if (ret == 0) {
                    let _sex = { 男: "0", 女: "1" };

                    this.ruleForm.nickName = Certificate.Name;
                    this.ruleForm.birthday = Certificate.Birthday.replace(/(\d{4})(\d{2})/, "$1-$2-"); // 出生日期
                    this.ruleForm.idIssued = Certificate.IDIssued; // 签发机关
                    this.ruleForm.issuedValidDate = Certificate.ValidDate.replace(/(\d{4})(\d{2})/, "$1-$2-")
                    this.ruleForm.sex = _sex[Certificate.Sex];
                    this.ruleForm.nation = Certificate.Nation + "族";
                    this.ruleForm.address = Certificate.Address;
                    this.ruleForm.certNumber = Certificate.IDNumber;
                    this.ruleForm.avatar = 'data:image/png;base64,' + Certificate.Base64Photo;

                    this.$message.success("读取成功！");
                    // this.id1 =
                } else if (ret in errors) {
                    this.$message.error(errors[ret]);
                } else {
                    this.$message.error("其他错误");
                }
            })
                .catch(err => {
                    l.close();
                    this.$message.error("未知错误");
                });
        }
    }
}
</script>
<style scoped>
.el-form-content {
    display: flex;
    padding: 40px 40px 0 40px;
    max-width: 1100px;
}
.el-form-items {
    flex: 1;
}
.el-form-items .el-form-item {
    margin-bottom: 20px;
    padding: 0 30px;
}
.el-form-items .el-select,
.el-form-items .el-date-editor {
    width: 100%;
}
.btns {
    text-align: center;
    max-width: 1100px;
    padding-top: 10px;
}
.user-code {
    display: flex;
    justify-content: space-between;
    margin-left: 130px;
    padding-right: 30px;
}
.user-code img {
    display: block;
    margin: 0 auto;
}
.user-code p {
    width: 100%;
    font-size: 14px;
    line-height: 20px;
    margin: 0 0 10px 0;
}
.user-code button {
    width: 120px;
    padding: 10px 0;
}
#qrcode {
    padding: 5px;
}
</style>